﻿function startPage() {

    $('.taskGroup .threedot, .taskSingle .threedot').dotdotdot();

    //combo da escolha do sprint
    var link = $('#comboSelectSprint').find('a').attr('href') + '/';
    $('#comboSelectSprint').comboselect({
        textButtom: $('#comboSelectSprint').find('.selecionado').html()
    });
    $('#comboSelectSprint').find('li.sprint').click(function () {
        window.location = link + ($(this).find('input[name="IdSprint"]').val())
    });

    //carregar os conteúdos dos itens;
    OpenEditTask($('table.tableboardmain'));
    CarregarConteudoItem($('div.scrumboaritem'));


    //acoes do menu
    $('#menuNovosItens > li.task').click(function () {
        OpenTask(0,0);
    });


    function CarregarConteudoItem(objContainer) {
        objContainer.each(function () {
            var container = $(this);
            $.ajax({
                url: 'ScrumBoard/ContentItemBoard/' + $(this).find(' > .boardtitleitem > input[name="IdItemBoard"]').val(),
                type: "GET",
                cache: false,
                success: function (dados, status, xhttp) {
                    container.find('tbody').html(dados);
                    OpenEditTask(container);
                    CarregarConteudoItem(container.find('div.scrumboaritem'))
                    CarregarConteudoSubTasks(container.find('> .tableboarditem > tbody > tr > .tasks > div.taskGroup'))
                    CriarSubItem(container);
                    
                }
            });
        });

        CriarExpandirItem(objContainer);
    }
    function CarregarConteudoSubTasks(objContainer) {
        
        objContainer.each(function () {
            var container = $(this);
            $.ajax({
                url: 'Task/ListSubTask/' + $(this).find(' > input[name="IdTask"]').val() + '/' + $(this).closest('td.tasks').find('> input[name="intState"]').val(),
                type: "GET",
                cache: false,
                success: function (dados, status, xhttp) {
                    container.find('> .interno > .listSubTask').html(dados);

                    CarregarConteudoSubTasks(container.find('> .interno > .listSubTask > div.taskGroup'))
                    OpenEditTask(container);
                }
            });
        });

        CriarExpandirTask(objContainer);
    }

    /* aplicar a ação de expandir dos itens */
    function CriarExpandirItem(container) {
        //TODO: implementar textos javascript vir dos recursos
        $(container).find(".boardtitleitem li.hideShow").click(function (ev) {
            $(this).closest('div.scrumboaritem').find('> table').toggle();
            if ($(this).closest('div.scrumboaritem').find('> table').is(':visible'))
                $(this).addClass('open').removeClass('close').attr('title', 'fechar');
            else
                $(this).addClass('close').removeClass('open').attr('title', 'abrir');

            ev.stopPropagation();
        }).attr('href', 'javascript:void(0);')

        $(container).find(".boardtitleitem li.btnTask").click(function (ev) {
            var idParent = $(this).closest('.boardtitleitem').find('input[name="IdItemBoard"]').val();
            OpenTask(0, idParent);
        });

    };

    function CriarExpandirTask(container) {
        $(container).find("a.hideShow").click(function (ev) {
            if ($(this).closest('div.interno').parent().hasClass('taskGroup')) {
                $(this).closest('div.interno').parent().removeClass('taskGroup').addClass('taskSingle');
            } else if ($(this).closest('div.interno').parent().hasClass('taskSingle')) {
                $(this).closest('div.interno').parent().removeClass('taskSingle').addClass('taskGroup');
            }
            ev.stopPropagation();
        }).attr('href', 'javascript:void(0);')


    }

    /* incluir um icone de referencia de que é "filho" de um item anterior */
    function CriarSubItem(sObject) {
        var lista = $(sObject).parents('div.scrumboaritem');
        if (lista.length <= 0)
            return;

        for (i = 0; i < lista.length; i++) {
            //TODO: implementar textos javascript vir dos recursos
            sObject.find('> .boardtitleitem > .subs').append($('<li title="sub"></li>'))
        }
        //indicar o passo "pai"
        sObject.find('li:last-child').mouseover(function () {
            $(this).closest('div.scrumboaritem').closest('table').closest('div.scrumboaritem').addClass('oversub')
        })
        sObject.find('li:last-child').mouseout(function () {
            $(this).closest('div.scrumboaritem').closest('table').closest('div.scrumboaritem').removeClass('oversub')
        })

    };

    function OpenEditTask(container) {
        SelectRemaingWork('.taskSingle, .taskGroup');

        container.find('.taskGroup > .interno > header > h1 > .btnEdit').click(function () {
            //carregar a task
            var id = $(this).closest('.taskGroup').find(' > input[name="IdTask"]').val();
            OpenTask(id)

        }).attr('href', 'javascript:void(0);');
        container.find('.taskSingle > .interno > header > h1 > .btnEdit').click(function () {
            //carregar a task
            var id = $(this).closest('.taskSingle').find(' > input[name="IdTask"]').val();
            OpenTask(id)

        }).attr('href', 'javascript:void(0);');
    }
    //TODO: melhorar tudo isso aqui
    function OpenTask(idTask, idParent) {
        var url;

        if(!idTask || idTask <= 0)
            url = 'Task/NewTask/' + idParent;
        else
            url = 'Task/EditTask/' + idTask;

        $.ajax({
            url: url,
            type: "GET",
            cache: false,
            success: function (dados, status, xhttp) {
                $('body').append(dados);


                var botaoSalvar = $('#TaskEdit').find('button[type="submit"]').val();
                $('#TaskEdit').find('button[type="submit"]').remove();

                var botoes = {};
                botoes[botaoSalvar] = function () {
                    $('#TaskEdit form').submit();
                }

                $('#TaskEdit').dialog({
                    autoOpen: false, modal: true,
                    width: 400, height: 350,
                    position: ['center', 'center'],
                    draggable: true, resizable: true,
                    close: function () {
                        $('#TaskEdit').dialog('destroy');
                        $('#TaskEdit').remove();
                    }
                });
                $('#TaskEdit').dialog("option", "buttons", botoes);

                $('#TaskEdit form').submit(function (e) {
                    $.ajax({
                        url: $(this).attr('action'),
                        data: $(this).serialize(),
                        type: "POST",
                        cache: false,
                        success: function (dados, status, xhttp) {
                            $('#TaskEdit').html($(dados).html());
                        }
                    });
                    e.preventDefault();
                });

                $('#TaskEdit').dialog('open');
            }
        });
    }

    function SelectRemaingWork(container) {
        //alert(container);
        $(container).mouseleave(function () {
            $(container).find(' > div.interno > footer > .comboSelectRemaing ').comboselect('close');
        });
        $(container).find(' > div.interno > footer > .comboSelectRemaing ').comboselect({
            /*textButtom: $('#comboSelectSprint').find('.selecionado').html()*/
        });
        $(container).find(' > div.interno > footer > .comboSelectRemaing select ').sliderselect(
        {
            onSelect: function (obj, valor, option) {
                if (option.hasClass('dividir')) {
                    obj.closest('footer').find('.comboSelectRemaing .valor').addClass('dividir');
                } else {
                    obj.closest('footer').find('.comboSelectRemaing .valor').removeClass('dividir');
                }
                obj.closest('footer').find('.comboSelectRemaing .valor').html(valor);
            },
            onStop: function (obj) {
                obj.closest('footer').find('.comboSelectRemaing').comboselect('close');
                //salvar a tarefa
                var form = $('<form></form>');
                var id = obj.closest('.taskSingle').find('input[name="IdTask"]').val()
                var remaing = obj.closest('footer').find('select[name="RemainWork"]').val()
                form.append($('<input type="text" value="' + id + '" name="Id" />'))
                form.append($('<input type="text" value="' + remaing + '" name="RemainingWork" />'))

                form.submit(function (e) {
                    $.ajax({
                        url: 'Task/SalvarTask/',
                        data: $(this).serialize(),
                        type: "POST",
                        cache: false,
                        success: function (dados, status, xhttp) {
                            alert(dados);
                        }
                    });
                    e.preventDefault();
                });

                form.submit();
            }
        }
        );
    }
    /*

    $('.taskSingle').click(function () {
        //carregar a task
        var id = $(this).find('.taskid').text();
        $.ajax({
            url: 'Task/EditTask/' + id,
            type: "GET",
            cache: false,
            success: function (dados, status, xhttp) {
                $('body').append(dados);


                var botaoSalvar = $('#TaskEdit').find('button[type="submit"]').val();
                $('#TaskEdit').find('button[type="submit"]').remove();

                var botoes = {};
                botoes[botaoSalvar] = function () {
                    $('#TaskEdit form').submit();
                }

                $('#TaskEdit').dialog({
                    autoOpen: false, modal: true,
                    width: 400, height: 350,
                    position: ['center', 'center'],
                    draggable: true, resizable: true,
                    close: function () {
                        $('#TaskEdit').dialog('destroy');
                        $('#TaskEdit').remove();
                    }
                });
                $('#TaskEdit').dialog("option", "buttons", botoes);

                $('#TaskEdit form').submit(function (e) {
                    $.ajax({
                        url: $(this).attr('action'),
                        data: $(this).serialize(),
                        type: "POST",
                        cache: false,
                        success: function (dados, status, xhttp) {
                            $('#TaskEdit').html($(dados).html());
                        }
                    });
                    e.preventDefault();
                });

                $('#TaskEdit').dialog('open');
            }
        });

    });*/

    //implementar o drag and drop

    /*$(".tasks .postIt").draggable({ revert: true });
    $(".tasks.inprogress").droppable({
        accept: ".tasks.todo .postIt, .tasks.done .postIt",
        drop: function (event, ui) {
            ui.draggable.attr('style', '');
            ui.draggable.appendTo($(".tasks.inprogress  ul"));
            TaskToProgress(ui.draggable);
        }
    });

    $(".tasks.todo").droppable({
        accept: ".tasks.inprogress .postIt",
        drop: function (event, ui) {
            ui.draggable.attr('style', '');
            ui.draggable.appendTo($(".tasks.todo  ul"));
            TaskToTodo(ui.draggable);
        }
    });

    $(".tasks.done").droppable({
        accept: ".tasks.inprogress .postIt",
        drop: function (event, ui) {
            ui.draggable.attr('style', '');
            ui.draggable.appendTo($(".tasks.done  ul"));
            TaskToDone(ui.draggable)
        }
    });*/

    
    function TaskToProgress(obj) {
        var id = obj.find('.taskid').text();
        $.ajax({
            url: 'ScrumBoard/TaskToProgress',
            data: { Id: id },
            type: "POST",
            cache: false,
            success: function (dados, status, xhttp) {
                //alert($(dados).html());
            }
        });

    }
    function TaskToDone(obj) {
        var id = obj.find('.taskid').text();
        $.ajax({
            url: 'ScrumBoard/TaskToDone',
            data: { Id: id },
            type: "POST",
            cache: false,
            success: function (dados, status, xhttp) {
                //alert($(dados).html());
            }
        });

    }
    function TaskToTodo(obj) {
        var id = obj.find('.taskid').text();
        $.ajax({
            url: 'ScrumBoard/TaskToTodo',
            data: { Id: id },
            type: "POST",
            cache: false,
            success: function (dados, status, xhttp) {
                //alert($(dados).html());
            }
        });

    }


    
}
